package com.ado.abyss.core.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ado.abyss.core.constants.SysConstants;
import com.ado.abyss.core.dal.model.SysMenu;
import com.ado.abyss.core.manager.SysMenuManager;
import com.ado.abyss.core.service.SysMenuService;

@Service(value = "sysMenuService")
public class SysMenuServiceImpl implements SysMenuService {

	@Autowired
	@Qualifier(value = "sysMenuManager")
	private SysMenuManager sysMenuManager ;


	@Override
	public List<SysMenu> findByUser(String name) {
		if(name == null || "".equals(name) || SysConstants.ADMIN.equalsIgnoreCase(name)) {
			return sysMenuManager.findAll();
		}
		return sysMenuManager.findByUserName(name);
	}


	@Override
	public List<SysMenu> findTree(String userName, int menuType) {
		List<SysMenu> sysMenus = new ArrayList<>();
		List<SysMenu> menus = findByUser(userName);
		for (SysMenu menu : menus) {
			if (menu.getParentId() == null || menu.getParentId() == 0) {
				menu.setLevel(0);
				if(!exists(sysMenus, menu)) {
					sysMenus.add(menu);
				}
			}
		}
		sysMenus.sort((o1, o2) -> o1.getOrderNum().compareTo(o2.getOrderNum()));
		findChildren(sysMenus, menus, menuType);
		return sysMenus;
	}

	private void findChildren(List<SysMenu> SysMenus, List<SysMenu> menus, int menuType) {
		for (SysMenu SysMenu : SysMenus) {
			List<SysMenu> children = new ArrayList<>();
			for (SysMenu menu : menus) {
				if(menuType == 1 && menu.getType() == 2) {
					// 如果是获取类型不需要按钮，且菜单类型是按钮的，直接过滤掉
					continue ;
				}
				if (SysMenu.getId() != null && SysMenu.getId().equals(menu.getParentId())) {
					menu.setParentName(SysMenu.getName());
					menu.setLevel(SysMenu.getLevel() + 1);
					if(!exists(children, menu)) {
						children.add(menu);
					}
				}
			}
			SysMenu.setChildren(children);
			children.sort((o1, o2) -> o1.getOrderNum().compareTo(o2.getOrderNum()));
			findChildren(children, menus, menuType);
		}
	}
	
	private boolean exists(List<SysMenu> sysMenus, SysMenu sysMenu) {
		boolean exist = false;
		for(SysMenu menu:sysMenus) {
			if(menu.getId().equals(sysMenu.getId())) {
				exist = true;
			}
		}
		return exist;
	}



	@Override
	public boolean delete(SysMenu sysMenu) {
		boolean flag = sysMenuManager.deleteById(sysMenu.getId()) ;
		return flag;
	}


	@Override
	public boolean deleteBatch(List<SysMenu> sysMenus) {
		List<Long> ids = new ArrayList<Long>() ;
		for (SysMenu sysMenu : sysMenus) {
			ids.add(sysMenu.getId()) ;
		}
		boolean flag = sysMenuManager.deleteByIds(ids) ;
		return flag;
	}


	@Override
	public boolean save(SysMenu record) {
		boolean flag = sysMenuManager.save(record) ;
		return flag;
	}

}
